/*
 * Copyright (c) 2010, Nikolaus Moll
 * All rights reserved.
 */
package net.miblounge.gradecalculator.guicommon.layouts;

import com.trolltech.qt.core.QRect;
import com.trolltech.qt.core.QSize;
import com.trolltech.qt.gui.QLayout;
import com.trolltech.qt.gui.QLayoutItemInterface;
import com.trolltech.qt.gui.QWidget;

public class VerySimpleLayout extends QLayout {
	private QLayoutItemInterface item = null;
	private QWidget widget = null;

	public VerySimpleLayout(final QWidget parent) {
		super(parent);
	}

	@Override
	public void setGeometry(final QRect rect) {
		super.setGeometry(rect);
		if (item != null) {
			final QRect clientRect = new QRect(
				parentWidget().contentsMargins().left(),
				parentWidget().contentsMargins().top(),
				rect.width(),
				rect.height());
			widget.setGeometry(clientRect);
		}
	}
	
	public void setWidget(final QWidget widget)
	{
		this.widget = widget;
		addWidget(widget);
	}

	@Override
	public void addItem(final QLayoutItemInterface item) {
		if (this.item != null) {
			throw new IllegalStateException("Only one widget allowed for this layout");
		}

		this.item = item;
	}

	@Override
	public int count() {
		if (item != null) {
			return 1;
		} else {
			return 0;
		}
	}

	@Override
	public QLayoutItemInterface itemAt(final int index) {
		if (index != 0) {
			return null;
		}
		return item;
	}

	@Override
	public QSize sizeHint() {
		if (widget != null) {
			final int marginWidth = parentWidget().contentsMargins().left() + parentWidget().contentsMargins().right();
			final int marginHeight = parentWidget().contentsMargins().top() + parentWidget().contentsMargins().bottom();

			final QSize clientSizeHint = widget.sizeHint();

			final QSize size = new QSize(clientSizeHint.width() + marginWidth, clientSizeHint.height() + marginHeight);
			return size;
		} else {
			return new QSize(0, 0);
		}
	}

	@Override
	public QLayoutItemInterface takeAt(final int index) {
		if (index != 0) {
			return null;
		}
		final QLayoutItemInterface result = item;
		item = null;
		widget = null;
		return result;
	}

}
